﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;

namespace HF.Framework.Log
{
    /// <summary>
    /// 数据访问类LogData。
    /// </summary>
    public class LogData
    {
        #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "LogId", "LogContent", "LogType", "LogDatetime", "IsShowed" };
        private string tableName = "HF_Logs";
        private string keyField = "LogId";
        private string sqlString = "";

        #endregion
        
        #region  私有方法
        private void setParameter(LogEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@LogId", entity.LogId, typeof(string));
            sqlDataItem.AppendParameter("@LogContent", entity.LogContent, typeof(string));
            sqlDataItem.AppendParameter("@LogType", entity.LogType, typeof(string));
            sqlDataItem.AppendParameter("@LogDatetime", entity.LogDatetime, typeof(DateTime));
            sqlDataItem.AppendParameter("@IsShowed", entity.IsShowed, typeof(string));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

        public LogEntity GetLogEntity(DataRow dr)
		{
			LogEntity  entity=new LogEntity();
			string value="";
			entity.LogId=dr["LogId"].ToString();
			entity.LogContent=dr["LogContent"].ToString();
			entity.LogType=dr["LogType"].ToString();
			value=dr["LogDatetime"].ToString();
			if(string.IsNullOrEmpty(value)==false)
			{
				entity.LogDatetime=Convert.ToDateTime(value);
			}
			entity.IsShowed=dr["IsShowed"].ToString();
			return entity;
		}

        #endregion

        #region  构造函数
        public LogData()
        { }
        public static LogData GetInstance()
        {
            return new LogData();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(LogEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(LogEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string logId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, logId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="logId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string logId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, logId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="LogId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetLogTable(string logId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, logId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一个数据实体
        /// </summary>
        /// <param name="logId">主键Id</param>
        /// <returns>DataTable</returns>
        public LogEntity GetLogEntity(string logId)
        {
            DataTable dt = GetLogTable(logId);
            if (dt != null && dt.Rows.Count > 0)
            {
                return GetLogEntity(dt.Rows[0]);
            }
            return null;
        }
        public DataTable GetLogTable(DateTime startTime, DateTime endTime)
        {
            string tmpSql = "select * from  HF_Logs where LogDatetime between @startTime and @endTime order by LogDatetime desc";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@startTime", startTime, typeof(DateTime));
                sqlItem.AppendParameter("@endTime", endTime, typeof(DateTime));

                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region  扩展方法
        /// 获得当前日期,yyyymmdd
        /// </summary>
        /// <returns></returns>
        public static string GetNowDate()
        {
            return DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
        }
        public static string GetLogId()
        {
            Int64 result = 0;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_CreatAutoCodePro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@Auto_Type", "SysLog");
                ClientDBAgent agent = new ClientDBAgent();
                result=Convert.ToInt64(agent.ExecuteScalar(sqlItem));
                return GetNowDate()+result.ToString("00000000");

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //此处添加扩展方法
        public static void WriteLog(string logStr, string logType)
        {
            string isDebugHF = System.Configuration.ConfigurationSettings.AppSettings["IsDebug"];
            if (isDebugHF.ToLower() == "true")
            {
                LogEntity entity = new LogEntity();
                entity.LogId = GetLogId();
                entity.LogContent = logStr;
                entity.LogType = logType;
                ClientDBAgent agent = new ClientDBAgent();
                entity.LogDatetime = Convert.ToDateTime(agent.GetDBDateTime());//取服务器时间
                entity.IsShowed = "0";
                LogData.GetInstance().Insert(entity);
            }
        }
        /// <summary>
        ///  写应用程序服务日志
        /// </summary>
        /// <param name="Content">日志内容</param>
        /// <param name="msgtype">日志类型</param>
        public static void WriteAppServerLog(string Content, string msgtype)
        {
            string isDebugHF = System.Configuration.ConfigurationSettings.AppSettings["IsDebug"];
            if (isDebugHF.ToLower() == "true")
            {
                string sqlStr = "insert into HF_AppServerLog(Content,msgtype)values(@Content,@msgtype)";
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.AppendParameter("@Content", Content);
                sqlItem.AppendParameter("@msgtype", msgtype);

                sqlItem.CommandText = sqlStr;
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
        }
        public List<LogEntity> GetLogEntitys(DateTime startTime, DateTime endTime)
        {
            List<LogEntity> result = new List<LogEntity>();
            DataTable dt = GetLogTable(startTime, endTime);
            foreach (DataRow dr in dt.Rows)
            {
                LogEntity entity = GetLogEntity(dr);
                result.Add(entity);
            }
            return result;
        }
        #endregion
        #endregion
    }
}

